﻿/*
 * Created by SharpDevelop.
 * User: Matjaž
 * Date: 16.11.2008
 * Time: 15:12
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace gopher
{
	/// <summary>
	/// Description of ImenikOkno.
	/// </summary>
	public partial class ImenikOkno : Form
	{
		public string mojStreznik;
		public string mojSelektor;
		public string mojaVrata;
		public int mojTimeout;
		
		
		public ImenikOkno(string selektor, string streznik, string vrata, int iTimeout)
		{
			//
			// The InitializeComponent() call is required for Windows Forms designer support.
			//
			InitializeComponent();
			
			mojStreznik = streznik;
			mojSelektor = selektor;
			mojaVrata = vrata;
			mojTimeout = iTimeout;
		}
		
		static void SendCommand (Stream stream, string line)
		{
			//byte[] data = Encoding.UTF8.GetBytes (line + "\r\n");
			byte[] data = Encoding.ASCII.GetBytes (line + "\r\n");
			stream.Write (data, 0, data.Length);
		}
		
		static string ReadLine (Stream s)
		{
			List<byte> lineBuffer = new List<byte>();
			while (true)
			{
				int b = s.ReadByte();
				if (b == 10 || b < 0) break;
				if (b != 13) lineBuffer.Add ((byte)b);
			}
			//return Encoding.UTF8.GetString (lineBuffer.ToArray());
			return Encoding.ASCII.GetString (lineBuffer.ToArray());
		}
		
		void SearchClick(object sender, EventArgs e)
		{
			using (TcpClient client = new TcpClient (mojStreznik, Convert.ToInt32(mojaVrata)))
			using (NetworkStream n = client.GetStream())
			{
				SendCommand (n, "query "+searchBox.Text);
				List<string> imenik = new List<string>();
				StringBuilder SB = new StringBuilder();
				int x=1000;
				if (n.DataAvailable == false) Thread.Sleep(mojTimeout);
				while (n.DataAvailable)
				{
					string line = ReadLine(n);
					
					if (line.StartsWith("-201:"))
					{
					    line = line.Substring(5);
					}					
					else if (line.StartsWith("102:"))
					{
					    line = line.Substring(4);
					}
					else if (line.Equals("200:Ok."))
					{
					    line = "";
					}
					else if (line.StartsWith("200:"))
					{
					    line = line.Substring(4);
					}
					else line = ReadLine (n);
					
					//if (line == ".") break;
					SB.Append(line);
					SB.Append("\r\n");
					x--;
					if (n.DataAvailable == false) Thread.Sleep(mojTimeout);
				}
				resultBox.Text = SB.ToString();
				resultBox.Select(0,0);
			}
			resultBox.Focus();
		}
		
		void CloseClick(object sender, EventArgs e)
		{
			Close();
		}
		
		void ImenikOknoHelpRequested(object sender, HelpEventArgs hlpevent)
		{
			Help.ShowHelp(this, Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("\\"))+"\\Help\\gopher.chm", "html\\phonebook-dialog.htm");
		}
	}
}
